package com.mid;

import java.util.Stack;

/**
 * Created by Lxk on 2020/2/26.
 */
public class Solution394 {

    public String decodeString(String s) {
        if ("".equals(s)) {
            return "";
        }
        Stack<String> strStack = new Stack<>();
        Stack<Integer> numStack = new Stack<>();

        StringBuffer strSb = new StringBuffer();
        StringBuffer numSb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '[') {
                numStack.push(Integer.valueOf(numSb.toString()));
                numSb = new StringBuffer();
                if (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
                    strStack.push("");
                }
            } else if (s.charAt(i) == ']') {
                int num = numStack.pop();
                if (strSb.length() > 0) {
                    strStack.push(strSb.toString());
                }
                strSb = new StringBuffer();
                StringBuffer tmp = new StringBuffer();
                for (int k = 0; k < num; k++) {
                    tmp.append(strStack.peek());
                }
                for (int k = i + 1; k < s.length(); k++) {
                    if (s.charAt(k) >= 'a' && s.charAt(i) <= 'z' || s.charAt(k) >= 'A' && s.charAt(k) <= 'Z') {
                        tmp.append(s.charAt(k));
                        i = k;
                    } else {
                        break;
                    }
                }
                strStack.pop();
                if (strStack.isEmpty()) {
                    strStack.push(tmp.toString());
                } else {
                    strStack.push(strStack.pop() + tmp.toString());
                }
            } else if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                if (strSb.length() != 0) {
                    strStack.push(strSb.toString());
                    strSb = new StringBuffer();
                }
                numSb.append(s.charAt(i));
            } else {
                strSb.append(s.charAt(i));
            }
        }
        return strStack.size() > 0 ? strStack.peek() + strSb.toString() : strSb.toString();
    }

    public static void main(String[] args) {
        String input = "3[z]2[2[y]pq4[2[jk]e1[f]]]ef";
        Solution394 solution394 = new Solution394();
        System.out.println(solution394.decodeString(input));
    }

}


